package com.iqilu.ksd.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.andview.refreshview.XRefreshViewLiveFooter;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.dialog.widget.MaterialDialog;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.LiveActivity;
import com.iqilu.ksd.activity.LiveVideoActivity;
import com.iqilu.ksd.activity.live.PhotoActivity;
import com.iqilu.ksd.activity.live.SmallVideoActivity;
import com.iqilu.ksd.activity.live.TextActivity;
import com.iqilu.ksd.activity.live.VideoActivity;
import com.iqilu.ksd.activity.live.VoiceActivity;
import com.iqilu.ksd.adapter.LiveListAdapter;
import com.iqilu.ksd.bean.LiveItemBean;
import com.iqilu.ksd.bean.LiveVideoBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.UserRole;
import com.iqilu.ksd.utils.ArrayUtils;
import com.iqilu.ksd.utils.BaseUtils;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.FileUtils;
import com.iqilu.ksd.utils.ImageUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.KeyboardUtils;
import com.iqilu.ksd.utils.NetworkUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.muzhi.camerasdk.model.CameraSdkParameterInfo;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/11/21.
 */

public class LiveListFragment extends BaseFragment implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,View.OnClickListener,EasyPermissions.PermissionCallbacks{

    private static final String TAG = "LiveListFragment";

    private int id;
    private int userId;
    private UserBean user;
    private LinearLayout liveSlideView;
    private ArrayList<LiveVideoBean> videoList = null;
    private ImageView imgEmpty;
    private ImageView btAdd;
    private View mLine;
    private ImageView imgLine;
    private RecyclerView rvList;
    private XRefreshView xRefreshView;
    private LiveListAdapter adapter;
    private RelativeLayout layMain;

    private ArrayList<LiveItemBean> data = new ArrayList<>();
    private ArrayList<LiveItemBean> topData = new ArrayList<>();
    private ArrayList<LiveItemBean> allData = new ArrayList<>();

    private MediaPlayer mediaPlayer;
    private int voiceId;
    private boolean isPlaying = false;

    private String photoPath;
    private LigDialog ligDialog;

    private Timer timer;
    private TimerTask timerTask;
    private boolean isLoading = false;
    private boolean isRefreshing = false;

    private static final int TYPE_TEXT = 1;
    private static final int TYPE_PIC = 2;
    private static final int TYPE_VIDEO = 3;
    private static final int TYPE_VOICE = 4;

    private static final int CODE_VIDEO = 1;
    private static final int CODE_ALBUM = 2;
    private static final int CODE_PHOTO = 3;
    private static final int CODE_VIDEO_LOCAL = 4;
    private static final int CODE_OTHER = 9;

    private static final int LOAD_NEW = 1;
    private static final int LOAD_OLD = 2;
    private static final int PERPAGE = 10;

    private static final int AUTO_LOADDATA = 1;
    private static final int CODE_PERM = 1001;
    private CameraSdkParameterInfo mCameraSdkParameterInfo = new CameraSdkParameterInfo();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = ((MyApplication) context.getApplicationContext()).getUser();
        Bundle bundle = getArguments();
        id = bundle == null ? 0 : bundle.getInt("id");
        userId = bundle == null ? 0 : bundle.getInt("userid");
        videoList = (ArrayList<LiveVideoBean>) bundle.getSerializable("videoList");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(this);
        FileUtils.createOrExistsDir(CacheUtils.getVoiceDir(context));
        FileUtils.createOrExistsDir(CacheUtils.getPicDir(context));
        FileUtils.createOrExistsDir(CacheUtils.getVideoDir(context));
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_livelist, null);
        imgEmpty = getView(view,R.id.img_empty);
        btAdd = getView(view,R.id.bt_add);
        btAdd.setOnClickListener(this);
        mLine = getView(view,R.id.line);
        layMain = getView(view,R.id.lay_main);
        imgLine = (ImageView) view.findViewById(R.id.img_line);
        if (user != null && (user.getId() == userId || user.getRole() == UserRole.REPORTER)) {
            btAdd.setVisibility(View.VISIBLE);
            mLine.setVisibility(View.VISIBLE);
        } else {
            btAdd.setVisibility(View.GONE);
            mLine.setVisibility(View.GONE);
        }
        xRefreshView = getView(view, R.id.xRefreshView);
        rvList = getView(view,R.id.rv_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        adapter = new LiveListAdapter(this,user);
        adapter.setCustomLoadMoreView(new XRefreshViewLiveFooter(context));
        rvList.setAdapter(adapter);

        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onHeaderMove(double offset, int offsetY) {
                super.onHeaderMove(offset, offsetY);
                Log.i(TAG,"onHeaderMove offset="+offset+";offsetY="+offsetY);
                imgLine.setTop(offsetY);
            }

            @Override
            public void onRefresh() {
                super.onRefresh();
                data = new ArrayList<>();
                topData = new ArrayList<>();
                allData = new ArrayList<>();
                isRefreshing = true;
                getTopData(true);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                new LoadData(LOAD_OLD, false).execute();
            }
        });
        isRefreshing = true;
        if (videoList != null && videoList.size() > 1) {
            initHeader();
            adapter.setHeaderView(liveSlideView,rvList);
        }

        getTopData(true);
        autoLoad();
        return view;
    }

    private void initHeader() {
        liveSlideView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.fragment_livelist_slideview, null);
        LinearLayout layoutSlide = (LinearLayout) liveSlideView.findViewById(R.id.layout_slide);
        for (int i = 0; i < videoList.size(); i++) {
            final LiveVideoBean bean = videoList.get(i);
            RelativeLayout item = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.list_item_livelist_slide, null);
            RelativeLayout layoutThumb = (RelativeLayout) item.findViewById(R.id.layout_thumb);
            layoutThumb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((LiveActivity) getActivity()).setChoice(bean.getVideo());
                }
            });
            ImageView imgThumb = (ImageView) item.findViewById(R.id.img_thumb);
            TextView txtTitle = (TextView) item.findViewById(R.id.txt_title);
            imgThumb.setImageURI(Uri.parse(bean.getPoster()));
            txtTitle.setText("" + bean.getTitle());
            layoutSlide.addView(item);
        }
    }

    private void autoLoad() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = AUTO_LOADDATA;
                handler.sendMessage(message);
            }
        };
        timer.schedule(timerTask, 2000, 2000);
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == AUTO_LOADDATA && !isLoading) {
                new LoadData(LOAD_NEW, false).execute();
            }
        }
    };

    @AfterPermissionGranted(CODE_PERM)
    public void addLive() {
        String perms[] = {Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if(EasyPermissions.hasPermissions(context,perms)){
            showAddAlert();
        }else {
            EasyPermissions.requestPermissions(this,getString(R.string.per_con_live_additem),CODE_PERM,perms);
        }
    }

    private void showAddAlert() {
        final Dialog dialog = new Dialog(context, R.style.live_dialog);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.popu_live_dialog);
        GridView gridAdd = (GridView) window.findViewById(R.id.grid_add);
        int[] image = {R.drawable.live_photo, R.drawable.live_album, R.drawable.live_video, R.drawable.live_audio, R.drawable.live_word};
        List<HashMap<String, Object>> btList = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < image.length; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("img_thumb", image[i]);
            btList.add(map);
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(context, btList, R.layout.list_item_live_add, new String[]{"img_thumb"}, new int[]{R.id.img_thumb});
        gridAdd.setAdapter(simpleAdapter);
        gridAdd.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long mid) {
                dialog.dismiss();
                switch (position) {
                    case 0:
                        addPhoto();
                        break;
                    case 1:
                        addPicture();
                        break;
                    case 2:
                        selectVideo();
                        break;
                    case 3:
                        addAudio();
                        break;
                    case 4:
                        addText();
                        break;
                    case 5:
//                        dialog.dismiss();
                        break;
                    default:
                        dialog.dismiss();
                        break;
                }
            }
        });
    }

    private void addPhoto() {
        photoPath = CacheUtils.getPicDir(context) + System.currentTimeMillis() + ".jpg";
        Intent intent_photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent_photo.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(photoPath)));
        intent_photo.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(intent_photo, CODE_PHOTO);
    }

    private void addPicture() {
        initAlbumConfig(4);
        Intent intent_album = new Intent();
        intent_album.setClassName(context, "com.muzhi.camerasdk.PhotoPickActivity");
        Bundle b = new Bundle();
        b.putSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER, mCameraSdkParameterInfo);
        intent_album.putExtras(b);
        startActivityForResult(intent_album, CameraSdkParameterInfo.TAKE_PICTURE_FROM_GALLERY);
    }

    private void initAlbumConfig(int max_img) {
        mCameraSdkParameterInfo.setSingle_mode(false);
        mCameraSdkParameterInfo.setShow_camera(false);
        mCameraSdkParameterInfo.setCroper_image(false);
        mCameraSdkParameterInfo.setFilter_image(false);
        mCameraSdkParameterInfo.setMax_image(max_img);
    }

    private void selectVideo() {
        String str[] = {getString(R.string.live_add_video_camera), getString(R.string.live_add_video_local)};
        final ActionSheetDialog dialog = new ActionSheetDialog(context, str, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        addVideoFromCamera();
                        break;
                    case 1:
                        addVideoFromLocal();
                        break;
                    default:
                        break;
                }
                dialog.dismiss();
            }
        });
    }

    private void addVideoFromCamera() {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.setClass(context, SmallVideoActivity.class);
        startActivity(intent);
    }

    private void addVideoFromLocal(){
        Intent intent = new Intent();
        intent.setType("video/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, CODE_VIDEO_LOCAL);
    }

    private void addAudio() {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.setClass(context, VoiceActivity.class);
        startActivity(intent);
    }

    private void addText() {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.setClass(context, TextActivity.class);
        startActivity(intent);
    }

    public void toEditItem(int position){
        timer.cancel();
        showEditBox(position);
    }

    private void showEditBox(final int position) {
        LiveItemBean item = allData.get(position);
        View commentView = LayoutInflater.from(context).inflate(R.layout.popu_comment, null);
        final EditText commentContent = (EditText) commentView.findViewById(R.id.comment_content);
        commentContent.setFocusable(true);
        if (item.getType() == TYPE_TEXT) {
            commentContent.setText(Uri.decode(item.getBody()));
        } else {
            commentContent.setText(Uri.decode(item.getDescription()));
        }
        Button btSubmit = (Button) commentView.findViewById(R.id.bt_submit);
        final PopupWindow popuWindow = new PopupWindow(commentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        ColorDrawable bgDrawable = new ColorDrawable(0x000000);
        popuWindow.setBackgroundDrawable(bgDrawable);
        popuWindow.setOutsideTouchable(true);
        popuWindow.setFocusable(true);
        popuWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popuWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popuWindow.setAnimationStyle(R.style.comment_popu_animation);
        popuWindow.showAtLocation(layMain, Gravity.BOTTOM, 0, 0);
        commentContent.setFocusable(true);
        commentContent.requestFocus();
        KeyboardUtils.toggleSoftInput(context);
        btSubmit.setText(getString(R.string.auth_submit));
        btSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!NetworkUtils.isAvailable(context)) {
                    Toast.makeText(context, R.string.net_not_connected, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(commentContent.getText())) {
                    Toast.makeText(context, R.string.live_comment_empty, Toast.LENGTH_SHORT).show();
                } else {
                    editLiveItem(position, "" + commentContent.getText());
                    commentContent.setText("");
                    popuWindow.dismiss();
                }
            }
        });
    }

    private void editLiveItem(int position, final String body) {
        final LiveItemBean item = allData.get(position);
        String url = Api.URL_LIVE_EDITDETAIL;
        OkHttpUtils
                .post()
                .url(url)
                .addParams("id", "" + item.getId())
                .addParams("body", "" + Uri.encode(body))
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(context, getString(R.string.live_submiting));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                        Toast.makeText(context, R.string.live_edit_fail, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ligDialog.dismiss();
                        JSONObject jsonObject = null;
                        int result = 0;
                        try {
                            jsonObject = new JSONObject(response);
                            result = jsonObject.getInt("status");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (result == 1) {
                            if (item.getType() == TYPE_TEXT) {
                                item.setBody(body);
                            } else {
                                item.setDescription(body);
                            }
                            adapter.notifyDataSetChanged();
                            Toast.makeText(context, R.string.live_edit_success, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(context, R.string.live_edit_fail, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    public void toDelItem(int position){
        timer.cancel();
        showDelDialog(position);
    }

    public void showDelDialog(final int position){
        final MaterialDialog dialog = new MaterialDialog(context);
        dialog.content(getString(R.string.live_del))
                .btnText(getString(R.string.ensure), getString(R.string.cancel))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        delLiveItem(position);
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        autoLoad();
                        dialog.dismiss();
                    }
                }
        );
    }

    private void delLiveItem(final int position) {
        int mId = allData.get(position).getId();
        String url = Api.URL_LIVE_DETAIL + "?id=" + mId;
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(context, getString(R.string.live_deleting));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ligDialog.dismiss();
                autoLoad();
                Toast.makeText(context, R.string.live_del_fail, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                int result = 0;
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    result = jsonObject.getInt("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (result == 0) {
                    Toast.makeText(context, R.string.live_del_fail, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, R.string.live_del_success, Toast.LENGTH_SHORT).show();
                    allData.remove(position);
                    adapter.notifyDataSetChanged();
                }
                autoLoad();
            }
        });
    }

    public void toPlayVideo(String url) {
        if(NetworkUtils.isWifiConnected(context)){
            playVideo(url);
        }else if (NetworkUtils.isAvailable(context)){
            showSelectDialog(url);
        }else {
            playVideo(url);
        }
    }

    public void toPlayVoice(String url){
        if(isPlaying){
            mediaPlayer.stop();
        }
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.prepareAsync();
        isPlaying = true;
        adapter.notifyDataSetChanged();
    }

    public void stopPlayVoice(){
        if(isPlaying){
            mediaPlayer.stop();
            adapter.setVoiceId(-1);
            isPlaying = false;
            adapter.notifyDataSetChanged();
        }
    }

    private void showSelectDialog(final String url) {
        final MaterialDialog dialog = new MaterialDialog(context);
        dialog.content(getString(R.string.not_wifi))
                .btnText(getString(R.string.cancel), getString(R.string.continue_play))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        playVideo(url);
                        dialog.dismiss();
                    }
                }
        );
    }

    private void playVideo(String url){
        Intent intent = new Intent(context, LiveVideoActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    //获取置顶的直播
    private void getTopData(final boolean isRefresh) {
        String url = Api.URL_LIVE_DETAILTOPLIST + "?liveid=" + id + "&multiimg=1";
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                isLoading = true;
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                new LoadData(LOAD_NEW, isRefresh).execute();
            }

            @Override
            public void onResponse(String response, int id) {
                ArrayList<LiveItemBean> result = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<LiveItemBean>>(){});
                if (result != null && result.size() > 0) {
                    topData = result;
                }
                new LoadData(LOAD_NEW, isRefresh).execute();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CODE_PHOTO:
                    Intent intent_photo = new Intent(context, PhotoActivity.class);
                    intent_photo.putExtra("photoPath", photoPath);
                    intent_photo.putExtra("id", id);
                    startActivity(intent_photo);
                    break;
                case CameraSdkParameterInfo.TAKE_PICTURE_FROM_GALLERY:
                    if (data == null) return;
                    Intent intent_album = new Intent(context, PhotoActivity.class);
                    intent_album.putExtras(data.getExtras());
                    intent_album.putExtra("id", id);
                    startActivity(intent_album);
                    break;
                case CODE_VIDEO_LOCAL:
                    if (data == null) return;
                    Uri uri = data.getData();
                    Cursor cursor = context.getContentResolver().query(uri, null, null,null, null);
                    cursor.moveToFirst();
                    // 视频可能在movie或者Camera文件夹下
                    Log.i(TAG,"videopath2====>"+cursor.getString(2));
                    String videoPath = "/storage/emulated/0/DCIM/movie/"+cursor.getString(2);
                    if(!FileUtils.isFileExists(videoPath)){
                        videoPath = "/storage/emulated/0/DCIM/Camera/"+cursor.getString(2);
                    }
                    if(!FileUtils.isFileExists(videoPath)){
                        videoPath = "/storage/emulated/0/tencent/MicroMsg/WeiXin/"+cursor.getString(2);
                    }
                    if(FileUtils.isFileExists(videoPath)) {
                        String thumbpath = CacheUtils.getCacheDir(context) + System.currentTimeMillis() + ".jpg";
                        Bitmap bitmap = BaseUtils.getVideoThumbnail(videoPath);
                        ImageUtils.save(bitmap, thumbpath, Bitmap.CompressFormat.JPEG);
                        Intent intent = new Intent(context, VideoActivity.class);
                        intent.putExtra("id", id);
                        intent.putExtra("videoPath", videoPath);
                        intent.putExtra("thumbpath", thumbpath);
                        startActivity(intent);
                    }else {
                        Toast.makeText(context,R.string.live_video_path_err,Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.i(TAG,"onCompletion");
        isPlaying = false;
        adapter.setVoiceId(-1);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.per_con_live_additem))
                    .setTitle(getString(R.string.per_title))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setRequestCode(requestCode)
                    .build()
                    .show();
        }
    }

    class LoadData extends AsyncTask<Void, Void, Void> {
        ArrayList<LiveItemBean> result;
        int fb = 1; //1 表示获取比自定的id更新的内容 2表示获取比制定的id更老的内容 默认是 1
        int listorder = 0;
        boolean isEmpty = false;
        boolean isRefrash;

        public LoadData(int fb, boolean isRefrash) {
            this.fb = fb;
            this.isRefrash = isRefrash;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            isLoading = true;
            if (data.size() == 0) {
                listorder = 0;
            } else {
                if (fb == LOAD_NEW) {
                    listorder = data.get(0).getListorder();
                } else {
                    listorder = data.get(data.size() - 1).getListorder();
                }
            }
            Log.i(TAG, "listorder=" + listorder);
        }

        @Override
        protected Void doInBackground(Void... params) {
            Response response = null;
            String url = Api.URL_LIVE_DETAILLIST + "?liveid=" + id + "&listorder=" + listorder + "&fb=" + fb + "&version=1.1.1&multiimg=1";
            try {
                response = OkHttpUtils.get().url(url).tag(this).build().execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response != null) {
                try {
                    result = JSONUtils.requestList(response.body().string(), "data", new TypeToken<ArrayList<LiveItemBean>>(){});
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (!isRefrash && isRefreshing) {
                return;
            }
            if(fb == LOAD_NEW) {
                xRefreshView.stopRefresh();
            }else {
                xRefreshView.stopLoadMore();
            }
            imgEmpty.setVisibility(View.GONE);
            result = ArrayUtils.removeLiveSame(allData, result);
            if (result == null || result.size() == 0) {
                result = new ArrayList<>();
                isEmpty = true;
            } else {
                isEmpty = false;
            }
            if (fb == LOAD_NEW) {
                result.addAll(data);
                data = result;
            } else {
                data.addAll(result);
            }
            allData = new ArrayList<>();
            allData.addAll(topData);
            allData.addAll(data);
            isLoading = false;
            isRefreshing = false;
            if (allData.size() == 0) {
                imgEmpty.setVisibility(View.VISIBLE);
                adapter.setData(allData);
                adapter.notifyDataSetChanged();
                return;
            }
            if (isEmpty) {
                return;
            }
            imgLine.setVisibility(View.VISIBLE);
            adapter.setData(allData);
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_add:
                addLive();
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }
}
